package io.eyer.nio.core.event;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.channels.*;

/**
 * Created by 青木 on 2015/8/17.
 */
public class Acceptor extends NioAbstract<ServerSocketChannel> {
    private static Logger logger = LoggerFactory.getLogger(Acceptor.class);
    public Acceptor(ReactorPool reactorPool) throws IOException {
        super(reactorPool);
    }

    public void register(ServerSocketChannel serverSocketChannel) throws ClosedChannelException {
        if (this == currentThread()) {
            serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT);
        } else {
            registeredQueue.offer(serverSocketChannel);
            this.selector.wakeup();
        }
    }

    @Override
    protected void handleRegistered(ServerSocketChannel serverSocketChannel, Selector selector) throws ClosedChannelException {
        serverSocketChannel .register(selector, SelectionKey.OP_ACCEPT);
    }

    @Override
    public void handleKey(SelectionKey key) {
        try {
            if (key.isValid()) {
                if (key.isAcceptable()) {
                    reactorPool.register((SocketChannel) ((ServerSocketChannel) key.channel()).accept().configureBlocking(false));
                } else {
                    key.cancel();
                }
            }
        } catch (Exception e) {
            try {
                key.channel().close();
                key.cancel();
            } catch (IOException e1) {
                logger.error(e.getMessage(), e);
            }
            logger.error(e.getMessage(), e);
        }
    }

    @Override
    public Logger getLogger() {
        return logger;
    }


}
